package dianmobile.eistarandroid.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dianmobile.eistarandroid.ByhhAndroidApplication;
import dianmobile.eistarandroid.R;
import dianmobile.eistarandroid.beans.PostsIntroduction;
import dianmobile.eistarandroid.network.request.BoardContentRequest;
import dianmobile.eistarandroid.network.request.RequestCallback;
import dianmobile.eistarandroid.ui.Adapter.BoardContentAdapter;
import dianmobile.eistarandroid.ui.views.SwipeActivity;
import dianmobile.eistarandroid.utils.ConstantsData;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

public class BoardContentActivity extends SwipeActivity {

    private List<PostsIntroduction> contentList = new ArrayList<>();
    private ZrcListView boardContentList;
    private BoardContentAdapter adapter;
    private String boardName;
    private ImageButton btnBack;
    private TextView tvBoardName;
    private EditText edtSearchInput;
    private ImageButton btnSearch;
    private ImageButton btnWrite;

    private int startNum = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ByhhAndroidApplication application = (ByhhAndroidApplication) getApplication();
        application.getActivityList().add(this);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_board_content);

        btnBack = (ImageButton)findViewById(R.id.btn_back);
        tvBoardName = (TextView)findViewById(R.id.tv_board_name);
        edtSearchInput = (EditText)findViewById(R.id.edt_search_input);
        btnSearch = (ImageButton)findViewById(R.id.btn_search);
        btnWrite = (ImageButton)findViewById(R.id.btn_write_article);

        boardContentList = (ZrcListView)findViewById(R.id.lv_board_content);

        Intent intent = getIntent();
        boardName = intent.getStringExtra(ConstantsData.EXTRA_BOARD_NAME);
        tvBoardName.setText(boardName);

        setPullToRefresh();
        adapter = new BoardContentAdapter(BoardContentActivity.this, contentList);
        boardContentList.setAdapter(adapter);
        boardContentList.refresh();
//        refresh();

        boardContentList.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                contentList.get(position).setRead(true);
                adapter.notifyDataSetChanged();
                Intent intent = new Intent(BoardContentActivity.this, ViewPostActivity.class);
                intent.putExtra(ConstantsData.EXTRA_FILE_NAME, contentList.get(position).getFile());
                intent.putExtra(ConstantsData.EXTRA_BOARD_NAME, boardName); //TODO 考虑传入summary，以供回复时使用
                startActivity(intent);
            }
        });

        TitleClickListener titleClickListener = new TitleClickListener();
        btnBack.setOnClickListener(titleClickListener);
        btnSearch.setOnClickListener(titleClickListener);
        btnWrite.setOnClickListener(titleClickListener);
    }

    @Override
    public void onDestroy() {
        ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
        application.getActivityList().remove(this);
        super.onDestroy();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (1 == requestCode && resultCode == RESULT_OK) {
            refresh();
        }
    }
    private void refresh() {
        Map<String, String> params = new HashMap<>();
        params.put(ConstantsData.EXTRA_BOARD_NAME, boardName);
        params.put(ConstantsData.EXTRA_START_NUM, "0");


        BoardContentRequest.execute(this, params, new RequestCallback() {
            @Override
            public void onResult(Map<String, Object> result, String error) {
                if (error != null) {
                    boardContentList.setRefreshFail("网络错误");
                } else {
                    boardContentList.setRefreshSuccess();
                    startNum = 1;
                    contentList.clear();
                    contentList.addAll((List<PostsIntroduction>) result.get(ConstantsData.ARTICLE_LIST));
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }
    /**
     * 加载更多数据，每页20条
     */
    private void loadMore(){
        Map<String, String> params = new HashMap<>();
        params.put(ConstantsData.EXTRA_BOARD_NAME, boardName);

        startNum += 20;
        params.put(ConstantsData.EXTRA_START_NUM, Integer.toString(startNum));

        BoardContentRequest.execute(this, params, new RequestCallback() {
            @Override
            public void onResult(Map<String, Object> result, String error) {
                if (error != null) {
                    boardContentList.setLoadMoreSuccess();
                    Toast.makeText(BoardContentActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                } else {
                    boardContentList.setLoadMoreSuccess();
                    contentList.addAll((List<PostsIntroduction>) result.get(ConstantsData.ARTICLE_LIST));
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }
    /**
     * config the pull-to-refresh and load more at end
     */
    private void setPullToRefresh() {
        // 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(this);
        header.setTextColor(0xff0066aa);
        header.setCircleColor(0xff33bbee);
        boardContentList.setHeadable(header);

        SimpleFooter footer = new SimpleFooter(this);
        footer.setCircleColor(0xff33bbee);
        boardContentList.setFootable(footer);
        boardContentList.startLoadMore();


        // 下拉刷新事件回调
        boardContentList.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                refresh();
            }
        });

        // 加载更多事件回调

        boardContentList.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                loadMore();
            }
        });
    }

    class TitleClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_back:
                    BoardContentActivity.this.finish();
                    break;
                case R.id.btn_search:
                    if (tvBoardName.isShown()) {
                        tvBoardName.setVisibility(View.INVISIBLE);
                        edtSearchInput.setText("");
                        edtSearchInput.setVisibility(View.VISIBLE);
                        btnSearch.setBackgroundResource(R.drawable.ic_close);
                    } else {
                        tvBoardName.setVisibility(View.VISIBLE);
                        edtSearchInput.setVisibility(View.INVISIBLE);
                        btnSearch.setBackgroundResource(R.drawable.ic_search);
                    }
                    break;
                case R.id.btn_write_article:
                    Intent intent = new Intent(BoardContentActivity.this, PostArticleActivity.class);
                    intent.putExtra(ConstantsData.EXTRA_POST_TYPE, ConstantsData.POST_TYPE_NEW);
                    intent.putExtra(ConstantsData.EXTRA_BOARD_NAME, boardName);
                    startActivityForResult(intent, 1);
                    break;
                default:
                    break;
            }
        }
    }
}
